package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

// 一条路由
type _Route struct {
	method  string
	path    string
	handler gin.HandlerFunc
}

// 使用每个文件里的 init 往里推 route
var routes []_Route

// 向 routes 里添加一条路由
func newRoute(method string, path string, handler gin.HandlerFunc) {
	routes = append(routes, _Route{method, path, handler})
}

// 向 routes 里添加一条 GET 路由
func _GET(path string, handler gin.HandlerFunc) {
	newRoute("GET", path, handler)
}

// 向 routes 里添加一条 GET 路由
func _POST(path string, handler gin.HandlerFunc) {
	newRoute("POST", path, handler)
}

// 向 routes 里添加一条 DELETE 路由
func _DELETE(path string, handler gin.HandlerFunc) {
	newRoute("DELETE", path, handler)
}

func main() {
	engine := gin.Default()
	engine.Use(func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE")
		c.Header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization")
		c.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers, Cache-Control, Content-Language, Content-Type")
		c.Header("Access-Control-Allow-Credentials", "true")

		if c.Request.Method == "OPTIONS" {
			c.AbortWithStatus(http.StatusNoContent)
		}
		c.Next()
	})
	// 会先执行包内各文件的 init，把 routes 填充
	for _, route := range routes {
		engine.Handle(route.method, route.path, route.handler)
	}
	engine.Run()
}
